//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.authine.cloudpivot.engine.component.aspect;

import com.authine.cloudpivot.app.api.facade.ApplicationFacade;
import com.authine.cloudpivot.engine.api.exceptions.LicenseException;
import com.authine.cloudpivot.engine.api.exceptions.ServiceException;
import com.authine.cloudpivot.engine.api.facade.BizSchemaFacade;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.component.LicenseLoader;
import com.authine.cloudpivot.engine.component.context.LicenseGlobalContext;
import com.authine.cloudpivot.engine.component.context.LicenseGlobalContext.LicenseVerifyCode;
import com.authine.cloudpivot.engine.component.service.LicenseService;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.license.LicenseInfo.ControlPattern;
import com.authine.cloudpivot.engine.license.LicenseInfo.LicenseType;
import com.authine.cloudpivot.engine.service.permission.LicensePermService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(1)
@Component
public class LicenseValidate {
    private static final Logger log = LoggerFactory.getLogger(LicenseValidate.class);
    @Autowired
    public BizSchemaFacade bizSchemaService;
    @Autowired
    private ApplicationFacade appPackageService;
    @Autowired
    private LicensePermService licensePermService;
    @Value("${cloudpivot.license.perm-manage.enabled:false}")
    private boolean permManageEnabled;
    @Autowired
    private LicenseLoader licenseLoader;
    @Autowired
    private LicenseService licenseService;
    @Autowired
    private UserFacade userFacade;
    @Autowired
    private LicenseGlobalContext licenseGlobalContext;

    public LicenseValidate() {
    }

    private boolean isProd() {
        return LicenseType.PROD.getType() == this.licenseGlobalContext.getInstance().getLicenseType();
    }

    @Pointcut("execution(public * com.authine.cloudpivot.engine.api.facade..WorkflowInstanceFacade.*(..))|| execution(public * com.authine.cloudpivot.engine.api.facade..AppManagementFacade.*(..))|| execution(public * com.authine.cloudpivot.engine.api.facade..BizObjectFacade.*(..))|| execution(public * com.authine.cloudpivot.engine.api.facade..BizServiceFacade.*(..))")
    public void validLicenseVerifyCodeResult() {
        log.trace("校验用户数量... ");
    }

    @Before("validLicenseVerifyCodeResult()")
    public void beforeValidLicense(JoinPoint joinPoint) {
        if (!this.licenseGlobalContext.getInstance().isOnline()) {
            String value = this.licenseGlobalContext.getInstance().getLicenseStatus();
            if (this.isProd() && (value == null || !value.equals("OK"))) {
                log.warn("许可证无效，授权验证失败！");
                throw new LicenseException(ErrCode.SYS_LICENSE_INVALID);
            } else {
                try {
                    String expirationStr = this.licenseGlobalContext.getInstance().getExpiration();
                    if (StringUtils.isEmpty(expirationStr)) {
                        synchronized(this.licenseLoader) {
                            if (StringUtils.isEmpty(this.licenseGlobalContext.getInstance().getExpiration())) {
                                log.info("许可证信息还未加载，加载一次许可证信息...");
                                this.licenseLoader.loadLicense(false);
                            }

                            expirationStr = this.licenseGlobalContext.getInstance().getExpiration();
                        }
                    }

                    Date expiration = (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(expirationStr);
                    Date date = new Date();
                    if (date.after(expiration)) {
                        log.warn("许可证授权日期已经过期，授权验证失败！expiration: {}", expiration);
                        throw new LicenseException(ErrCode.SYS_LICENSE_EXPIRE);
                    }
                } catch (ParseException var7) {
                    log.warn("许可证授权日期错误，授权验证失败！");
                    throw new LicenseException(ErrCode.SYS_LICENSE_INVALID);
                }

                if (this.licenseGlobalContext.getInstance().getLicenseVerifyCodeResults().contains(LicenseVerifyCode.MORE_THAN_AUTH_USER_NUMBER)) {
                    throw new ServiceException(ErrCode.OVER_LICENSE_USER_NUM.getErrCode(), LicenseVerifyCode.MORE_THAN_AUTH_USER_NUMBER.getDesc());
                } else {
                    if (this.licenseGlobalContext.getInstance().isTempLicense()) {
                        int demoWorkflowInstanceNumber = 100000;
                        if (this.licenseService.getWorkflowInstanceNumber() > demoWorkflowInstanceNumber) {
                            throw new ServiceException(ErrCode.WORKFLOW_INSTANCE_NUMBER_OVER.getErrCode(), String.format(LicenseVerifyCode.MORE_WORKFLOW_INSTANCE_NUMER.getDesc(), Integer.valueOf(demoWorkflowInstanceNumber)));
                        }
                    }

                }
            }
        }
    }

    @Pointcut("execution(public * com.authine.cloudpivot.engine.api.facade..AppManagementFacade.addAppPackage(..))")
    public void validAppNumber() {
        log.trace("开启检查应用数量... ");
    }

    @Before("validAppNumber()")
    public void beforeValidAppNumber(JoinPoint joinPoint) {
        log.trace("检查应用数量是否超过授权数量... ");
        Integer licenseAppNum = this.licenseGlobalContext.getInstance().getAppNumber();
        long appCount = this.appPackageService.getAppPackageNumber();
        if (appCount >= (long)licenseAppNum) {
            throw new LicenseException(ErrCode.APP_PACKAGE_OVER_LICENSE_APPNUM);
        }
    }

    @Pointcut("execution(public * com.authine.cloudpivot.engine.api.facade..AppManagementFacade.addAppFunction(..))")
    public void validSchemaNumber() {
        log.trace("开启检查模型数量... ");
    }

    @Before("validSchemaNumber()")
    public void beforeValidSchemaNumber(JoinPoint joinPoint) {
        log.trace("检查模型数量是否超过授权数量... ");
        long licenseSchemaNum = (long)this.licenseGlobalContext.getInstance().getSchemaNumber();
        long count = this.bizSchemaService.count();
        if (count >= licenseSchemaNum) {
            throw new LicenseException(ErrCode.APP_FUNCTION_OVER_LICENSE_SCHEMA_NUM);
        }
    }

    @Pointcut("execution(public * com.authine.cloudpivot.engine.api.facade..OrganizationFacade.syncOrganization(..))")
    public void validUserNumber() {
        log.trace("开启检查用户数量... ");
    }

    @Before("validUserNumber()")
    public void beforeValidUserNumber(JoinPoint joinPoint) {
        Integer controlPattern = this.licenseGlobalContext.getInstance().getControlPattern();
        if (!this.permManageEnabled && ControlPattern.ONLINE.getType() != controlPattern) {
            int licenseUserNum = this.licenseGlobalContext.getInstance().getUserNumber();
            int userNum = this.userFacade.getTotalNum();
            if (userNum > licenseUserNum) {
                throw new LicenseException(ErrCode.OVER_LICENSE_USER_NUM);
            }
        }
    }

    @Pointcut("execution(public * com.authine.cloudpivot.web.api.controller.login.LoginController.getCode(..))")
    public void validOnlineUserNumber() {
        log.trace("开启检查在线用户数量... ");
    }

    @Before("validOnlineUserNumber()")
    public void beforeValidOnlineUserNumber(JoinPoint joinPoint) {
        Integer controlPattern = this.licenseGlobalContext.getInstance().getControlPattern();
        if (ControlPattern.ONLINE.getType() == controlPattern) {
            int licenseUserNum = this.licenseGlobalContext.getInstance().getUserNumber();
            int userNum = this.licenseService.getOnlineUserNumber();
            if (userNum >= licenseUserNum) {
                throw new LicenseException(ErrCode.OVER_LICENSE_ONLINE_USER_NUM, String.format(ErrCode.OVER_LICENSE_ONLINE_USER_NUM.getErrMsg(), licenseUserNum, userNum));
            }
        }
    }
}
